<script>
	import api from '@/api'
	import uniRequest from 'uni-request';
	import checkUpdate from "@/uni_modules/uni-upgrade-center-app/utils/check-update"
	// #ifdef APP-PLUS
	import MYSQL from '@/common/mysqlite.js'
	// #endif
	// #ifdef H5
	import MYSQL from '@/common/myIndexedDB.js'
	// #endif
	//websocket心跳器
	let Interval = null,
	errorConnectionTimes = 0;
	// 
	let newMsgHis = {}, msgPopupInterval = null
	let allFindMembers = uni.getStorageSync('allFindMembers');
	export default {
		components: {
		},
		globalData: {  
			isStudent: true,
			baseInfo: {},
			userInfo: {},
			
			msgTips: {},
			examinActivity: [],
			bdxs_shbyrwdss: {},
			msgTipsTrim: null,
			receiveMsgId: '',
			taskPageIndex: 0,
			teamMembersPairType: -1, // 结对列表默认页面
			taskPageTime: -1,
			disLineMsgInfo: {},
			mysql: MYSQL,
			platform: '',
			deleteHis: 0,
			boardHeight: 0,
			isRefreshContent: false
		},
		onLaunch: async function() {
			uni.onKeyboardHeightChange(res => {
				this.globalData.boardHeight = res.height
				// console.log(res.height)
			})
			uni.onTabBarMidButtonTap(()=>{
				console.log("点击了", this.globalData.userInfo);
				if(this.globalData.userInfo.user_type==1){
					uni.navigateTo({
						url: '/pages/teachers/publish-page'
					})
				}else{
					uni.navigateTo({
						url: '/pages/student/publish-page'
					})
				}
				
			})
			// #ifdef APP-PLUS
			this.globalData.platform = uni.getSystemInfoSync().platform
			uni.onNetworkStatusChange( (res) => { // 监听断线，记录断线时间
				this.listeneroffLine(res.isConnected)
			});

			uni.removeStorageSync('xdGroupList')
			this.Mshow()
			uni.$on('Mhide', ()=>{
				this.Mhide()
			})
			// #endif
			getApp().globalData.mysql.initDB();
			
			//获取基本参数
			this.getBaseInfo();
			//更新
			checkUpdate();
			//监听消息
			uni.$on('getMsgTips', (fn)=>{
				this.getMsgTips(fn);
			})
			/*
  * 后端接收的消息类型:0心跳,1实时私聊,2实时群聊,3获取私聊历史消息,4获取群聊历史消息,5离线消息
  * ws发往前端的消息类型:0其他,1实时聊天消息,2历史消息,3通知消息,4错误消息,5离线消息,6推送
  * 
  * 字符消息（binaryType = blob）过来后会走这个方法
  * {
  *     "requestEventType": "事件类型: 0心跳,1实时私聊,2实时群聊,3获取私聊历史消息,4获取群聊历史消息,5离线消息,6阅读状态,7撤回",
  *     "msgType": "消息类型(0:text、1:image、2:voice、3:vedio、4:music、5:news、6:share,7, 表情, 8: 文档，9：@)",
  *     "to":"目标ID",
  *     "groupId": "群组id",
  *     "beginTime": "消息区间开始时间戳",
  *     "endTime":"消息区间结束时间戳",
  *     "offset":"分页偏移量int类型",
  *     "count": "显示消息数量",
  *    "content" :"内容,JSON对象"
  *     "extras": "扩展字段,JSON对象格式如：{'扩展字段名称':'扩展字段value'}"
  *  }
  */
			/*
			 * sendSocketMessage发送的格式
			 * ws消息类型:0.心跳,1.发消息,2.历史消息,3.离线消息
			 * {
				   "from": "来源ID",
				   "to": "目标ID",
				   "eventType":"1",
				   "createTime": "消息创建时间long类型",
				   "msgType": "消息类型int类型(0:text、1:image、2:voice、3:vedio、4:music、5:news)",
				   "chatType":"聊天类型int类型(0:未知,1:公聊,2:私聊)",
				   "groupId":"群组id仅在chatType为(1)时需要,String类型",
				   "content": "内容",
				   "extras" : "扩展字段,JSON对象格式如：{'扩展字段名称':'扩展字段value'}"
				}
				{
					"eventType":"0",
					"hbbyte":"心跳1个字节"
				}
				{
					 "eventType":"2",
					 "fromUserId":"消息发送用户id(此字段必须与userId一起使用,获取双方聊天消息),非必填",
					 "userId":"当前用户id(必填字段)",
					 "groupId":"群组id(此字段必须与userId一起使用,获取当前用户指定群组聊天消息),非必填",
					 "beginTime":"消息区间开始时间Date毫秒数double类型,非必填",
					 "endTime":"消息区间结束时间Date毫秒数double类型,非必填",
					 "offset":"分页偏移量int类型，类似Limit 0,10 中的0,非必填",
					 "count":"显示消息数量,类似Limit 0,10 中的10,非必填"
				}
				{
					 "eventType":"3" //离线消息是一次性获取所有的，一般不用
				}
			 */
			//登录监听
			uni.$on('login',(data) =>{
				allFindMembers = uni.getStorageSync('allFindMembers')
				let newTokenObj = uni.getStorageSync('tokenObj');
				if(newTokenObj.wsToken){
					//初始websocket链接
					let socketTask = uni.connectSocket({
						url: `${this.api.wsUrl}?token=${newTokenObj.wsToken}`,
						fail: (e) => {
							console.log(e)
						}
					})
					uni.onSocketOpen((res) => {
						console.log('WebSocket连接已打开！', this.api.wsUrl);
						errorConnectionTimes = 0; // 连接成功之后把错误连接次数清零
						if (Interval){
							clearInterval(Interval);
						}
						Interval = setInterval(() => {
							if(!uni.getStorageSync('tokenObj')){
								console.log("清理定时")
								clearInterval(Interval);
								uni.closeSocket({
									code: 1000
								});
							}else{
								if(socketTask.readyState == 3) {
									console.log("重连")
									socketTask = uni.connectSocket({
										url: `${this.api.wsUrl}?token=${newTokenObj.wsToken}`,
										fail: () => {}
									})
								}else{
									uni.sendSocketMessage({
										data: JSON.stringify({returnEventType: 0})//心跳
									});
								}
							}
						}, 10000);
						// alert(141)
						let xdDisNetworkTime = uni.getStorageSync('xdDisNetworkTime') || {};
						let obj = xdDisNetworkTime[this.globalData.userInfo.id] || {};
						this.offLineData(this.globalData.userInfo.id, obj)
					});
					uni.onSocketClose((res) =>{
						// alert(141)
						console.log('WebSocket 已关闭！', res);
					});
					uni.onSocketError((res) =>{
						// 错误连接次数不能超过10次
						if(errorConnectionTimes==10) return;
						errorConnectionTimes += 1;
						socketTask = uni.connectSocket({
							url: `${this.api.wsUrl}?token=${newTokenObj.wsToken}`,
							fail: () => {}
						})
					});
					uni.onSocketMessage((res) => {
						//"requestEventType": "事件类型: 0心跳,1实时私聊,2实时群聊,3获取私聊历史消息,4获取群聊历史消息,5离线消息,6阅读状态,7撤回",
						// 前端接收 0其他,1实时聊天消息,2历史消息,3通知消息,4错误消息,5离线消息,6推送,7系统配置,8阅读状态,9群成员变化,10撤回
						// gmv群消息。pmv私聊消息
						if(!allFindMembers){
							allFindMembers = uni.getStorageSync('allFindMembers')
						}
						let o = JSON.parse(res.data);
						console.log(o)
						let nmh = uni.getStorageSync('newMsgHis') || null;
						newMsgHis = nmh?nmh:newMsgHis
						let userId = this.globalData.userInfo.accountId;
						let sessionIdValue = ''
						if(o.returnEventType == 0){
							// 版本升级
						}else if(o.returnEventType == 1){
							let tableName = '', data = {},
								chatId = '', newMsgId = '', userTypeVal='';
							
							if(o.chatTyp == 2){ // 私聊
								data = o.privateMsgList[0]
								// userId 是当前用户的wsId, chatId是私聊者的wsid或者群id
								chatId = data.from==userId ? data.to:data.from
								userTypeVal = allFindMembers[chatId]?allFindMembers[chatId].userType:'';
								// 缓存在本地

								tableName = userTypeVal==1 ? 'totmsg' : userTypeVal==2?'tosmsg' : 'topmsg'
								if(data.to==userId){
									let toUserInfo = allFindMembers[chatId] || {}
									this.showTips(1, data, toUserInfo)
								}

								newMsgId = `${chatId}${userId}`
								let toUserType = userTypeVal
								// data.sessionId = `${chatId}-${userId}`
							}else{
								data = o.groupMsgList[0]
								chatId = data.groupId
								tableName = 'togroupmsg'
								if(data.from != userId){
									// this.showTips(3,data.msgType, data.content, data.from, chatId)
								}
								newMsgId = `${userId}${chatId}`
							}
							// 记录最新消息
							if(newMsgHis[newMsgId]){
								newMsgHis[newMsgId].data = [data]
							}else{
								newMsgHis[newMsgId] = {}
								newMsgHis[newMsgId].data = [data]
							}
							
							if(data.from!=userId){ // 对方发给自己的消息，记录数量
								if(newMsgHis[newMsgId].count){
									newMsgHis[newMsgId].count = newMsgHis[newMsgId].count+1;
									
								}else{
									newMsgHis[newMsgId].count = 1
								}
							}
							
							getApp().globalData.mysql.addData(tableName, data, function(res){
								// console.log(243, res, allFindMembers, chatId)
							})

							uni.setStorageSync('newMsgHis', newMsgHis);
							// uni.$emit('newMsgHis', newMsgHis)
							
							// #ifdef APP-PLUS
							if(data.msgType == 1 || data.msgType == 2 || data.msgType == 3 || data.msgType==8)
							// #endif
							// #ifdef H5
							if((data.msgType==1 || data.msgType == 3) && (!data.extras || !JSON.parse(data.extras).dst_path))
							// #endif
							{
								this.getDownloadUrl(data, tableName, function(){
									uni.$emit('privateChat', {msg:o})
								})
							}else if(data.msgType==6){
								if(JSON.parse(data.content).img.indexOf('chat/')==-1) return
								this.getDownloadUrl(data, tableName, function(){
									uni.$emit('privateChat', {msg:o})
								})
							}else{
								uni.$emit('privateChat',{msg:o});
							}
							
						}else if(o.returnEventType == 2){
							let that = this;

							let list = o.privateMsgList || o.groupMsgList;
							function func(a, b){
								return a.createTime-b.createTime;
							}
							list.sort(func)
							let msgType = ''
							// ,privateChat
							uni.$emit('privateChat', {msg:o})
	
							
							
							
						}else if(o.returnEventType == 3){
							/* 1, 学生提交每日任务;   [1条待审核任务]
								2, 学生提交每周任务;  [1条待审核任务]
								3, 学生提交每月任务;  [1条待审核任务]
								4, 学生绑定教师申请;  [1条绑定请求]
								5, 教师审核榜样;      重要他人审核已完成，请点击查看
								6, 教师审核每日任务;  每日任务审核已完成，请点击查看
								7, 教师审核每周任务;  每周任务审核已完成，请点击查看
								8, 教师审核每月任务;  每月任务审核已完成，请点击查看
								9, 教师通过/拒绝学生绑定申请;   教师绑定申请审核已完成，请点击查看
								10, 学生创建重要他人； [重要他人待审核]
								11, 学生解绑导师       [学生已解绑导师]
							*/
							let data = JSON.parse(o.content);
							
							let avatarUrl = data.pic||'';
							let params = data.type<4||data.type==10?data.taskInfos:data.type==4?data.id:data.type>5&&data.type<9?data.taskTime:'';

							this.taskNotice(data, data.type, data.name, avatarUrl, data.sex, params)
						}else if(o.returnEventType == 4){
							let errMsg = JSON.parse(o.content).errMsg
							uni.showToast({
								title: errMsg.msg,
								icon: 'none',
								duration: 2000,
								mask: true
							});
						}else if(o.gmv&&o.gmv.returnEventType == 5){
							
							
							// let xdDisNetworkTime = uni.getStorageSync('xdDisNetworkTime') || {};
							// let obj = xdDisNetworkTime[this.globalData.userInfo.id] || {};
							// // console.log(obj, 267)
							// if(obj.start){
							// 	this.globalData.disLineMsgInfo = o;
								
							// 	return 
							// }
							let msgSet = [], id = '', tableName = '';
							let newMsgId = ''
							let disLineData = this.globalData.disLineMsgInfo;
							if(Object.keys(disLineData).length>0){
								o.gmv.groupMsgList.concat(disLineData.gmv.groupMsgList)
								o.pmv.privateMsgList.concat(disLineData.pmv.privateMsgList)
							}
							for (const key in o) {
								let len = 0
								if(key == 'pmv'){
									len = o.pmv.privateMsgList.length
									if(len>0){
										id = o.pmv.privateMsgList[0].from
										msgSet = o.pmv.privateMsgList
										let userTypeVal = allFindMembers[id]?allFindMembers[id].userType:'';
										if(this.globalData.isStudent){
											tableName = userTypeVal==1 ? 'totmsg':'topmsg'
										}else{
											tableName = userTypeVal==2?'tosmsg':'topmsg'
										}
									}
									newMsgId = `${id}${userId}`
									this.handleMsg(o.pmv.privateMsgList, tableName, 'from', userId, newMsgHis)
								}else{
									tableName = 'togroupmsg'
									len = o.gmv.groupMsgList.length
									if(len>0){
										id = o.gmv.groupMsgList[0].groupId
										msgSet = o.gmv.groupMsgList
									}
									newMsgId = `${userId}${id}`
									this.handleMsg(o.gmv.groupMsgList, tableName, 'groupId', userId, newMsgHis)
								}
							}
						}else if(o.returnEventType == 6){
							
						}else if(o.returnEventType == 8){
							let data = JSON.parse(o.content)
							// userId 是当前用户的wsId, chatId是私聊者的wsid或者群id
							let arr = data.sessionId.split('-');

							var toid = arr[0]==data.fromUserId?arr[1]:arr[0]
							let userTypeVal = allFindMembers[toid]?allFindMembers[toid].userType:'';
							let tableName = data.groupId?'togroupmsg':gettableName(userTypeVal)
			
							// data.sessionId = `${toid}-${data.fromUserId}`
					
							// console.log(347, tableName)
							data.extras = '{}'
							getApp().globalData.mysql.isRead(tableName, data, function(res){
									// console.log(370, res)				
							})
							uni.$emit('privateChat', o)
						}else if(o.returnEventType == 10){
							let data = JSON.parse(o.content)
							let tableName = data.groupId?'togroupmsg':'';
							let userTypeVal = '';
							if(!tableName){

								let arr = data.sessionId.split('-');
								var toId = arr[0]==data.from?arr[1]:arr[0]
								userTypeVal = allFindMembers[toId]?allFindMembers[toId].userType:''
								// console.log(373, userTypeVal,toId )
								tableName = gettableName(userTypeVal)
								// data.sessionId = `${toId}-${data.from}`
							}
							
							
							for (const key in newMsgHis) {
								let hisData = newMsgHis[key].data[0]
								if (hisData.sessionId == data.sessionId && hisData.createTime == data.createTime) {
									hisData.content = ''
									// newMsgHis[key] = hisData
									// console.log(370, hisData)
								}
							}
							let idName = data.groupId?'groupId':'sessionId'

							// getApp().globalData.mysql.deleteLine(tableName, idName, `${userTypeVal}-${data.sessionId}`, data.createTime, function(res1){
								
							// })
							// console.log(372, newMsgHis, tableName, data)
							data.content = ''
							uni.setStorageSync('newMsgHis', newMsgHis);
							// console.log(404, tableName)
							getApp().globalData.mysql.update(tableName, data, function(res){
								// console.log(402, res, tableName)
							})
							uni.$emit('privateChat', o)
						}else if(!o.returnEventType){
							let listS = o.offLineMsgStateS || [];
							for(let i=0; i<listS.length; i++){
								let tableName = data.groupId?'togroupmsg':'';
								if(!tableName){
									let toId = data.sessionId.split('-')[0]==userId?data.sessionId.split('-')[1]:data.sessionId.split('-')[0]
									let userTypeVal = allFindMembers[toId]?allFindMembers[toId].userType:''
									tableName = gettableName(userTypeVal)
								}
								
								getApp().globalData.mysql.isRead(tableName, data, function(res){})
							}
						}
						function gettableName(type){
							return type==1?'totmsg':type==2?'tosmsg':'topmsg'
						}
						this.utils.showRedDot(newMsgHis, userId)

						
					});
				}
			})
			
			
			let tokenObj = uni.getStorageSync('tokenObj');
			if(tokenObj){
				let loginTime = tokenObj.loginTime || 0;
				let diff = new Date().getTime()-loginTime
				
				if(loginTime>0 && diff>14*24*60*60*1000){
					uniRequest.defaults.headers.common['Token'] = ''
				}
				//请求获取个人信息
				let type = tokenObj.userType;
				let token = tokenObj.token;
				this.globalData.isStudent = type==2?true:false;
				
				this.getMsgTips(null);
				// #ifdef H5
				this.api.get('user/getMeInfo').then(res=>{
					let info = res.data.user
					this.globalData.userInfo = info;
					if(info.user_type==2){
						this.utils.setSTabBar();
					}else if(info.user_type==1){
						this.utils.setTTabBar();
					}
					
				})
				// #endif
				uni.$emit('login',{});
			}else{//跳转角色选择
				// uni.reLaunch({
				// 	url: '/pages/index/select-role'
				// })
			}
			
			
			
			
		},
		onShow: function() {

			
			
			// setInterval(()=>{
				
			// }, 1000)
			// var Profile = Vue.extend({
			//   template: '<p>{{firstName}} {{lastName}} aka {{alias}}</p>',
			//   data: function () {
			//     return {
			//       firstName: 'Walter',
			//       lastName: 'White',
			//       alias: 'Heisenberg'
			//     }
			//   }
			// })
			// // 创建 Profile 实例，并挂载到一个元素上。
			// new Profile().$mount('#mount-point')
			// #ifdef H5
			window['listeneroffLine'] = (isConnected) => {
				this.listeneroffLine(isConnected)
			}
			// #endif
		},
		onHide: function() {},
		methods: {
			getMsgTips(fn){
				if(this.globalData.isStudent) return;
				this.api.get('tip/msgTips').then(res=>{
					let tips = res.data || {};
			

					this.globalData.msgTips = tips.unExaminTask;
					this.globalData.examinActivity = tips.unExaminActivity;

					let count = tips.unExaminTask.length
					if(count>0){
						// uni.showTabBarRedDot({index: 1})
					}

					tips.bdxs = tips.bdxs.concat(tips.jbxs)
					this.globalData.bdxs_shbyrwdss = {bdxs: tips.bdxs,shbyrwdss: tips.shbyrwdss, shbydss: tips.shbydss};
					let shNum = tips.bdxs.length+tips.shbyrwdss.length+tips.shbydss.length;
					if(shNum>0){
						// uni.showTabBarRedDot({index: 2})
						setTimeout(()=>{
							// uni.showTabBarRedDot({index: 2})
						}, 100)
					}
					if(fn){
						fn(tips.unExaminTask)
					}
				})
			},
			listeneroffLine(isConnected){
				let xdDisNetworkTime = uni.getStorageSync('xdDisNetworkTime') || {};
				let obj = xdDisNetworkTime[this.globalData.userInfo.id] || {};
					// alert(isConnected)
				if(!isConnected){
					
					obj = {start: parseInt(new Date().getTime()/1000)};
					
					
				}else{
					if(obj.start){
						
						obj.end = parseInt(new Date().getTime()/1000)
						xdDisNetworkTime[this.globalData.userInfo.id] = obj;

					}
				}
				xdDisNetworkTime[this.globalData.userInfo.id] = obj;
				uni.setStorageSync('xdDisNetworkTime', xdDisNetworkTime)
			},
			offLineData(userId, obj){
				let disTime = obj || {};
				if(disTime.start>0){
					
							// alert(JSON.stringify(disTime.start))
					let beginTime = disTime.end>0?disTime.end:disTime.start + 30
					let data = {
						"requestEventType": 5,
						"beginTime": disTime.start,
						"endTime": beginTime
					}
					uni.sendSocketMessage({
						data: JSON.stringify(data),
						success: ()=>{
							if(beginTime-disTime.start>30 || !disTime.end){
								this.getOffLineMsg()
							}
							
						}
					});
					let xdDisNetworkTime = uni.getStorageSync('xdDisNetworkTime') || {};
					xdDisNetworkTime[userId] = {}
					// delete xdDisNetworkTime[userId]
					uni.setStorageSync('xdDisNetworkTime', xdDisNetworkTime)
				}else{
					this.getOffLineMsg()
				}
					
			},
			getOffLineMsg(){
				let data = {
					"requestEventType": 5
				}
				uni.sendSocketMessage({
					data: JSON.stringify(data),
					success: ()=>{
						
					}
				});
			},
			getBaseInfo(){
				this.api.get('base/getBaseInfo').then(res=>{
					let orgGrades = res.data.orgGrades;
					let newOrgGraders = []
					for (const key in orgGrades) {
						let list = orgGrades[key].class;
						if (list.length>0) {
							for(let i=0; i<list.length; i++){
								let obj = {}, item = list[i]
								obj[item.id] = `${orgGrades[key].name}${item.name}`
								newOrgGraders.push(obj)
							}
							
						}
					}
					
					res.data.newOrgGraders = newOrgGraders;
					getApp().globalData.baseInfo = res.data;
				})
			},
			handleMsg(list, tableName, idName, userId, newMsgHis){
				// alert(JSON.stringify(list))
				let obj = {},
				newMsgId = '',
				emitNumber = 0
				for(let i=0; i<list.length; i++){
					newMsgId = list[i][idName]
					newMsgId = idName=='from'?`${newMsgId}${userId}`:`${userId}${newMsgId}`;
					if(!obj[newMsgId]){
						obj[newMsgId] = []
					}
					obj[newMsgId].push(list[i])
				}
				for (const key in obj) {
					let len = obj[key].length;
					if(len>0){
						getApp().globalData.mysql.addmData(tableName, obj[key], function(res){
							if(res){
								if(emitNumber==1)return;
								emitNumber = 1
								uni.$emit('newMsgHis', newMsgHis)
							}
						})
					}
					if(newMsgHis[key]){
						len = len + newMsgHis[key].count
						
					}else{
						newMsgHis[key] = {}
					}
					newMsgHis[key].count = len
					newMsgHis[key].data = obj[key]
				}
				// alert(JSON.stringify(newMsgHis))
				uni.setStorageSync('newMsgHis', newMsgHis);
				
				// uni.$off('privateChat', {})
			},
			taskNotice(info, type,name, pic, sex, params){
				var pages = getCurrentPages();
				var page = pages[pages.length - 1];
				let userTypeVal = 2,
				text = '',
				path = ''
				if(type < 4){
					userTypeVal = 1;
					sex = 1;
					text = '[1条待审核任务]';
					path = `/pages/teachers/${type==1?'audit-details':type==2?'week-audit-details':'month-audit-details'}?stuId=${info.id}&state=1&date=${this.utils.initDateDay()}&name=${name}`;
					let msgTips = getApp().globalData.msgTips || {}
					
					let list = [], date = this.utils.initDateDay();
					let taskInfo = params[0] || {}
					let taskIdList = taskInfo.taskIdList || []
					for(let i=0; i<taskIdList.length; i++){
						let obj = {time: date, id: taskIdList[i]}
						list.push(obj)
					}
					if(type==1){
						msgTips.day = msgTips.day.concat(list)
					}else if(type == 2){
						if(taskInfo.taskType==1){
							msgTips.week.mzrws = msgTips.week.mzrws.concat(list)
						}else{
							msgTips.week.tbfxs = msgTips.week.tbfxs.concat(list)
						}
					}else if(type == 3){
						msgTips.month = msgTips.month.concat(list)
					}
					getApp().globalData.msgTips = msgTips;
					uni.$emit('tipsData', type-1)
					
					if(path.indexOf(page.route) !=-1) return;
				}else if(type == 4){
					userTypeVal = 2;
					text = `[1条${info.pairType==1?'结对':'解绑'}申请]`;
					path = '/pages/teachers/team-members?pairType='+info.pairType
					
					if(params>0){
						// let bdxsShbyrwdss = getApp().globalData.bdxs_shbyrwdss;
						getApp().globalData.bdxs_shbyrwdss.bdxs.push(params)
						getApp().globalData.teamMembersPairType = info.pairType
						// getApp().globalData.bdxs_shbyrwdss = bdxsShbyrwdss;
						if(page.route == 'pages/teachers/team-members') {
							getApp().globalData.taskPageIndex = info.pairType
							
						};
						uni.$emit('uncheckNumber')
					}
					
					if(page.route == 'pages/teachers/team-members') return;
				}else if(type == 5){
					if(page.route == 'pages/student/example-details') return;
					userTypeVal = 1;
					sex = 1;
					text = '[重要他人审核已完成，点击查看]';
					path = '/pages/student/example-details'
				}else if(type > 5 && type < 9){
					userTypeVal = 1;
					sex = 1;
					text = `${type==6?'每日':type==7?'每周':'每月'}任务审核已完成，点击查看`;
					path = '/pages/student/task-page?parmas=tabBar'
					let index = type-6
					getApp().globalData.taskPageTime = params
					getApp().globalData.taskPageIndex = index;
					if(page.route == 'pages/student/task-page') {
						let t = 0
						if(index == 1){
							t = 500
						}
						setTimeout(()=>{
							uni.$emit('noticeListener', index)
						}, t)
						return};
				}else if(type == 9){
					if(page.route == 'pages/student/bind-history'){
						uni.$emit('noticeListener')
						return;
					} 
					userTypeVal = 1;
					sex = 1;
					text = `[教师${info.pairState==2?'通过':'拒绝'}${info.pairType==1?'结对':'解绑'}申请]`;
					path = '/pages/student/bind-history'
					
				}else if(type == 10){
					// params
					userTypeVal = 2;
					text = '[重要他人待审核]';
					path = '/pages/teachers/example-list'
					let dsh = getApp().globalData.bdxs_shbyrwdss;
					for(let i=0; i<params.length; i++){
						if(params[i].taskType==3){
							let list = dsh.shbydss.concat(params[i].taskIdList)
							dsh.shbydss = Array.from(new Set(list));
						}else{
							let list = dsh.shbyrwdss.concat(params[i].taskIdList);
							
							dsh.shbyrwdss = Array.from(new Set(list));
						}
					}
					getApp().globalData.bdxs_shbyrwdss = dsh;
					// uni.showTabBarRedDot({index: 2})
					uni.$emit('uncheckNumber')
					if(page.route == 'pages/teachers/example-list') return;
					
				}
				if(!text) return
				let userinfo = {name: name, userType: userTypeVal, sex: sex}
				this.showTipsPopup(pic, text, path, userinfo)
			},
			showTips(type, data, info){
				// msgType, text, fromId, wsId
				let msgType = data.msgType;
				let text = this.utils.emojiName(data, info.accountId)
				var pages = getCurrentPages();
				var page = pages[pages.length - 1];
				let receiveId = getApp().globalData.receiveMsgId
				if(receiveId == data.from) return;
				if(type == 1){
					// 一对一的私聊消息
					// this.getTeacherMsgList(text)
					// let id = fromId - 100000;

					let avatarUrl = info.avatarUrl||''
					let params = (page.route== 'pages/chatSystem/chat-page' || page.route== 'pages/chatSystem/group-msg')?'redirect':''
					let path = `/pages/chatSystem/chat-page?toUserType=${info.userType}&id=${info.id}&name=${info.name}&accountId=${info.accountId}&avatarUrl=${avatarUrl}&sex=${info.sex}&params=${params}`
					
					this.showTipsPopup(avatarUrl, text, path, info)
				}else if(type == 3){
					// 群聊消息
					if(page.route == 'pages/chatSystem/group-msg') return;
					this.getGroupInfo(wsId, text)
				}
			},
			getGroupInfo(id, text){
				let groupList = uni.getStorageSync('xiaode_friend_list') || [];
				let item = {}, userTypeVal = this.globalData.isStudent?2:1
				if(groupList.length>0){
					item = groupList.find(group => group.type&&group.id == id);
					let path = `/pages/chatSystem/group-msg?examId=${id}&type=${userTypeVal}`
					this.showTipsPopup(item.avatarUrl, text, path, item)
				}else{
					this.api.get(`chatGroupManage/findChatSession`).then(res=>{
						if(res.data.state != 'ok') return;
						let list = res.data.friends.concat(res.data.schoolChatGroup, res.data.familyChatGroup, res.data.commonChatGroup, res.data.exampleGroup);
						if(list.length>0){
							uni.setStorageSync('xiaode_friend_list', list)
							this.getGroupInfo(id, text)
						}
						
					})
				}
			},
			showTipsPopup(avatarUrl, text, path, info){
				let sex = info.sex==2?2:1
				avatarUrl = avatarUrl?this.api.xiaodeObsUrl+avatarUrl : info.userType?`/static/${info.userType==2?`stu${sex}`:'te1'}.png`:info.type==1?'/static/u16.png':'/static/txl/qlx1.png'
				// #ifdef H5
					this.utils.msgPopup(avatarUrl, text, info.name, path)
				// #endif
				// #ifdef APP-PLUS
				clearTimeout(msgPopupInterval)
				let params = {
					url: avatarUrl,
					tips: text,
					name: info.name
				}
				this.changeMsg(params);
				this.Mshow(path)
				msgPopupInterval = setTimeout(()=>{
					this.Mhide()
				}, 5000)
				// #endif
			},
			getDownloadUrl(data,tableName, fun){

				let content = data.content
				if(data.msgType == 6){
					
					content = `["${JSON.parse(content).img}"]`
				}else if(data.msgType == 8){
					let list = JSON.parse(data.content), conts = []
					for(let i=0; i<list.length; i++){
						conts.push(list[i].path)
					}
					content = JSON.stringify(conts)
				}else if(data.msgType == 2){
					content = JSON.stringify([JSON.parse(data.content)[0].path])
				}
				if(data.content[0]!='['){
					content = `["${data.content}"]`
				}
				this.api.get('file/getDownloadUrl', {
					fileNames: content,
					isThumbnail: data.msgType==1?true:false
				}).then(res=>{
					if(res.data.state != 'ok') return
					let downloadUrl = res.data.downloadUrl || {},
					urls = [];
					urls = Object.values(downloadUrl)

					// #ifdef APP-PLUS || H5
					for(let i=0; i<urls.length; i++){
						this.downloadFile(data,tableName, urls[i], fun)
					}
					
					// #endif
				})
			},
			
			downloadFile(data,tableName, downloadUrl, fun){
				uni.downloadFile({
					url: downloadUrl, //资源
					success: (res) => {
						if (res.statusCode === 200) {
							// console.log('下载成功', res);
							// #ifdef H5
							let extras = JSON.parse(data.extras);

							extras.dst_path = extras.dst_path?extras.dst_path:[]
							extras.dst_path.push(res.tempFilePath)
							
							this.$set(data, 'extras', JSON.stringify(extras))
							// uni.$emit('privateChat', {msg:o})
							fun()
							// #endif
							// #ifdef APP-PLUS
							uni.saveFile({
								tempFilePath: res.tempFilePath,
								success: (res1)=>{
									let dst_path = plus.io.convertLocalFileSystemURL(res1.savedFilePath)
									let extras = JSON.parse(data.extras);
									extras.dst_path = extras.dst_path?extras.dst_path:[]
									extras.dst_path.push(dst_path)
									this.$set(data, 'extras', JSON.stringify(extras))
									getApp().globalData.mysql.update(tableName, data, function(res){
										// console.log(903, res)
									})
									fun()
									// uni.$emit('privateChat', {msg:o})
								}
							})
							// #endif
						}
					}
				});
			},
		}
	}
// #ifdef H5
	let offline = null
window.addEventListener('online', () => {
//   offline.close()
  offline = true
  console.log('网络连接恢复')
  listeneroffLine(true)
//   uni.$emit('login',{});
})
window.addEventListener('offline', () => {
	offline = false
	listeneroffLine(false)
	// uni.closeSocket({
	// 	code: 1000
	// });
  console.log('网络连接失败')
})
// #endif
</script>

<style>
	/*每个页面公共css */
	@import '@/static/font/iconfont.css';
	@import './common/tribute.css';
	@import url("./common/style.css");
	@import url("./common/txl.css");
	
	page {
		
	 	color: #333333;
		background-color: #fff;
	 	 min-height: 100%;
	  	font-size: 28rpx;
	}
	/* #ifdef H5 */
	.fix-left-window {
		padding-left: var(--window-left);
	}
	.pc-hide {
		display: none !important;
	}
	@media screen and (min-width: 768px) {
		body {
			overflow-y: scroll;
		}
	}
	uni-page-body {
		background-color: #fff !important;
		min-height: 100% !important;
		height: auto !important;
	}
	
	.uni-top-window uni-tabbar .uni-tabbar {
		background-color: #fff !important;
	}
	
	.uni-app--showleftwindow .hideOnPc {
		display: none !important;
	}
	
	/* #endif */
	.tribute-name{
		color:#55acee;
	}
</style>
